#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "ohos_types.h"
#include "cmsis_os2.h"
#include <librws.h>
#include "wifi_sta.h"

#define WS_TASK_STACK_SIZE 3072
#define WS_TASK_PRIO 25

// 因主动或者出现错误时，断开连接的回调函数
static void on_socket_disconnected(rws_socket socket) {
    // process error
    rws_error error = rws_socket_get_error(socket);
    if (error) { 
        printf("Socket disconnect with code, error: %i, %s\n", rws_error_get_code(error), rws_error_get_description(error)); 
    }
    // forget about this socket object, due to next disconnection sequence
    socket = NULL;
}

// 建立链接完成后的回调函数
static void on_socket_connected(rws_socket socket) {
    (void) socket;
    printf("Socket connected\n");
}

// 接受到信息的回调函数
static void on_socket_received_text(rws_socket socket, const char * text, const unsigned int length) {
    (void) socket;
    char *buff[128] = {0};
    memcpy_s(buff, 128, text, length);
    printf("Socket text: %s\n", buff);
}

static void LibrwsTEST(const char *arg) {
    (void) arg;
    int ret;
    ret = hi_wifi_start_sta();
    if(ret == -1) {
        printf("[Wifi] Connect failed!\n");
    } else {
        printf("[Wifi] Connect sucess!\n");
    }
    sleep(5);

    rws_socket _socket = NULL;
    _socket = rws_socket_create();
    
    rws_socket_set_scheme(_socket, "ws");
    rws_socket_set_host(_socket, "192.168.1.103");
    rws_socket_set_port(_socket, 7777);
    rws_socket_set_path(_socket, "/ws");
    
    // 设置回调函数
    rws_socket_set_on_disconnected(_socket, &on_socket_disconnected); // required
    rws_socket_set_on_connected(_socket, &on_socket_connected);
    rws_socket_set_on_received_text(_socket, &on_socket_received_text);
    
    printf("[RWS]ready to connect\n");
    rws_bool res = rws_socket_connect(_socket);
    if(res == rws_false) {
        printf("[RWS]error connect\n");
        exit(1);
    }
    sleep(2);
    const char * example_text = "hello world";
    printf("[RWS]ready to send msg\n");
    rws_socket_send_text(_socket, example_text);
    sleep(2);
    printf("[RWS]ready to disconnect\n");
    rws_socket_disconnect_and_release(_socket);
    _socket = NULL;
    return;
}

static void LibrwsPthread(void) {
    osThreadAttr_t attr;

    attr.name = "WSTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = WS_TASK_STACK_SIZE;
    attr.priority = WS_TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)LibrwsTEST, NULL, &attr) == NULL) {
        printf("[LedExample] Falied to create WSTask!\n");
    }
}

SYS_RUN(LibrwsPthread);